import React from 'react';
import ReactDOM from 'react-dom';
import {connect,Provider} from 'react-redux'
import {createStore,combineReducers,applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga'
import * as effects from 'redux-saga/effects'
import createRootSaga from './rootSaga'
import createReducers from './createReducers'
import {createHashHistory} from 'history'

// import {prefix} from './utils'
export {connect}
// 增加命名空间前缀
function prefix(reducers,namespace){
    let newReducers = {}
    for(let key in reducers){
        newReducers[namespace+'/'+key] = reducers[key]
    }
    return newReducers
}
export default function(){
    const app ={
        _models:[], //存放所有模型
        model, //添加模型的方法
        _router:null, //存放所有路由
        router, //定义路由的方法
        start
    }
    function model(model){
        app._models.push(model);

    }
    function router(routerConfig){
        app._router = routerConfig

    }
    function start(selector){


        // let reducers = {}
        // for(let model of app._models){
        //     let {namespace,state:initialState,reducers:modelReducers} = model
        //     let reducersWithPrefix = prefix(modelReducers,namespace) //KEY已经增加了命名空间前缀
        //     reducers[namespace] = function(state=initialState,action){
        //         let reducer = reducersWithPrefix[action.type] //type='count/add'
        //         if(reducer){
        //             return reducer(state,action)
        //         } //如果reducer没有匹配上 说明axtion不是给我处理的  直接返回老状态
        //         return state
        //     }
        // }
        let rootReducers = createReducers(app._models)
        // let rootReducer = combineReducers(rootReducers)
        let sagaMiddleware = createSagaMiddleware()
        let rootSaga = createRootSaga(app._models)
        let store = createStore(rootReducers,applyMiddleware(sagaMiddleware))
        sagaMiddleware.run(rootSaga) //开始启动rootsaga执行
        let history = createHashHistory()
        let App = app._router({history})
        ReactDOM.render(
            <Provider store={store}>
                {App}
            </Provider>
        ,document.querySelector(selector))
    }
    return app
}
